package org.spider.core.executor.function.functionExtension;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.spider.api.annotation.Comment;
import org.spider.api.annotation.Example;
import org.spider.api.annotation.Return;
import org.spider.api.executor.FunctionExtension;
import org.spider.api.utils.http.SpiderResponse;
import org.spider.core.utils.ExtractUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ResponseFunctionExtension implements FunctionExtension {

    @Override
    public Class<?> support() {
        return SpiderResponse.class;
    }

    @Comment("将请求结果转为Element对象")
    @Example("${resp.element()}")
    public static Element element(SpiderResponse response) {
        return Jsoup.parse(response.getHtml(),response.getUrl());
    }

    @Comment("根据xpath在请求结果中查找")
    @Example("${resp.xpath('//title/text()')}")
    @Return({Element.class, String.class})
    public static String xpath(SpiderResponse response, String xpath) {
        return ExtractUtils.getValueByXPath(element(response), xpath);
    }

    @Comment("根据xpath在请求结果中查找所有文本")
    @Example("${resp.xpathAllText('//title')}")
    @Return({ String.class})
    public static String xpathAllText(SpiderResponse response, String xpath) {
        return ExtractUtils.getAllTextByXpath(element(response), xpath);
    }

    @Comment("根据xpath在请求结果中查找")
    @Example("${resp.xpaths('//a/@href')}")
    public static List<String> xpaths(SpiderResponse response, String xpath) {
        return ExtractUtils.getValuesByXPath(element(response), xpath);
    }

}
